import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    carRes: []
  },
  mutations: {
    // 增加食物
    addFoods (state, foodInfo) {
      let flag = false
      state.carRes.some(item => {
        if (item.id === foodInfo.id) {
          item.count = parseInt(foodInfo.count)
          flag = true
          return true
        }
      })
      if (!flag) {
        state.carRes.push(foodInfo)
      }
    },
    // 减少食物
    reFoods (state, foodInfo) {
      // 分析一哈 如果传过来的count = 0 则从carRes中删除这一个food，不等于则把这一项的foodinfo的count 赋值给carRes
      if (foodInfo.count === 0) {
        state.carRes.some((item, i) => {
          if (item.id === foodInfo.id) {
            state.carRes.splice(i, 1)
            return true
          }
        })
      } else {
        state.carRes.some((item, i) => {
          if (item.id === foodInfo.id) {
            item.count = foodInfo.count
            return true
          }
        })
      }
    },
    //  清空食物
    emptyFoods (state) {
      state.carRes.forEach(item => {
        item.count = 0
      })
      state.carRes = []
    }
  },
  getters: {
    // 写一下想法循环carres 让里面每一项的count相加
    allCount (state) {
      let c = 0
      state.carRes.forEach(item => {
        c += item.count
      })
      return c
    },
    allPrice (state) {
      // 如果还当前这一项就让
      let c = 0
      state.carRes.forEach(item => {
        c += item.price * item.count
      })
      return c
    }
  }
})
